package com.glorystone.ins.controller;

import com.glorystone.ins.common.CollectionForm;
import com.glorystone.ins.common.common.DataTable;
import com.glorystone.ins.common.common.PageVo;
import com.glorystone.ins.domain.*;
import com.glorystone.ins.enums.FlowBusinessTypeEnum;
import com.glorystone.ins.enums.FlowOperateTypeEnum;
import com.glorystone.ins.enums.RejectNodeEnum;
import com.glorystone.ins.enums.WorkFlowEnum;
import com.glorystone.ins.interceptor.PageList;
import com.glorystone.ins.service.*;
import com.glorystone.ins.vo.OperateResult;
import com.glorystone.ins.vo.RebateSetVo;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpServletRequest;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * 项目名称：ins
 * 类名称：ProductCtr
 * 类描述：产品 ProductCtr
 * 创建人：zgh
 * 创建时间：2018/3/12 14:18
 */
@Slf4j
@Controller
@RequestMapping("/product")
public class ProductCtr extends BaseController{

    /**
     * 产品
     */
    @Autowired
    private ProductSvr productSvr;

    /**
     * 保险公司
     */
    @Autowired
    private InsurerService insurerService;

    @Autowired
    private AuditTaskService auditTaskService;

    @Autowired
    private BusinessLogService businessLogService;

    @Autowired
    private CaculateService caculateService;

    @Override
    @InitBinder
    public void initBinder(WebDataBinder binder) {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        dateFormat.setLenient(false);
        binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true));
    }
    @RequestMapping(value = "/toList",method = RequestMethod.GET)
    public String toList(Model model,@RequestParam(defaultValue = "0",required = false)Integer  m){
        List<Insurer> insurerList = insurerService.selectAllInsurer();
        model.addAttribute("insurerLists",insurerList);
        model.addAttribute("m1",m);
        return "/product/product_list";
    }

    @RequestMapping(value = "/toList1",method = RequestMethod.GET)
    public String toList1(Model model){
        List<Insurer> insurerList = insurerService.selectAllInsurer();
        model.addAttribute("insurerLists",insurerList);
        model.addAttribute("m1",1);
        return "/product/product_list";
    }

    /**
     * 查询所有产品
     * @return
     */
    @RequiresPermissions(value = {
            "product:forPricing",
            "product:havePricing"
    }, logical = Logical.OR)
    @RequestMapping(value = "/list")
    @ResponseBody
    public DataTable<Product> getProjectList(Model model,
                                 @RequestParam(defaultValue = "0",required = false)Integer  t,
                                 HttpServletRequest request){
        log.info("-------传入参数product:t:"+t+"-------------");
        PageVo vo =  parametToPageVo(request, Product.class);
        PageList<Product> list = productSvr.findList(t,vo);
        DataTable data = resultToDataTable(list);
        log.info("-----------------结果集data"+data+"-------------------------------");
        return data;
    }

    /**
     * 查询所有保险公司
     * @param model
     * @return
     */
    @RequestMapping(value = "/toCreatePage")
    public String toCreatePage(Model model){
        List<Insurer> insurerList = insurerService.selectAllInsurer();
        model.addAttribute("types", 4);
        model.addAttribute("insurerList",insurerList);
        return "/product/product_list";
    }

    /**
     * 查询保险公司对应的业务员
     * @param tid
     * @return
     */
    @RequestMapping("/getSlaesmenByCompanyId")
    @ResponseBody
    public List<InsurerUser> getSlaesmenByCompanyId(Long tid){
        List<InsurerUser> userList = insurerService.getSlaesmenByCompanyId(tid);
        return userList;
    }
    /**
     * 新建产品
     * @param product
     * @return
     */
    @RequiresPermissions(value = "product:createProduct")
    @RequestMapping("/insert")
    @ResponseBody
    public OperateResult insertProject(Product product){
        log.info("-------传入参数product:"+product+"-------------");
        OperateResult result = productSvr.insert(product);
        return  result;
    }

    /**
     * 产品详情页
     * @param model
     * @param tid
     * @return
     */
    @RequestMapping("/getDetails")
    public String getDetails(Model model,Long tid){
        log.info("-------传入参数产品tid:"+tid+"-------------");
        Product product = productSvr.getProductByTid(tid);
        List<BusinessLog> businessLogList = businessLogService.findList(BusinessLog.BusinessTypeEnum.PRODUCT, tid);
        log.info("----------------查询出来产品信息product:"+product+"--------------------------");
        model.addAttribute("produ",product);
        model.addAttribute("types",5);
        model.addAttribute("businessLogList3",businessLogList);
        return "/product/product_list";
    }
    /**
     * 驳回产品详情页
     * @param model
     * @param tid
     * @return
     */
    @RequestMapping("/getRejectDetails")
    public String getRejectDetails(Model model,Long tid){
        log.info("-------传入参数产品tid:"+tid+"-------------");
        Product product = productSvr.getRejectProductByTid(tid);
        List<BusinessLog> businessLogList = businessLogService.findList(BusinessLog.BusinessTypeEnum.PRODUCT, tid);
        log.info("----------------查询出来产品信息product:"+product+"--------------------------");
        model.addAttribute("produ",product);
        model.addAttribute("types",5);
        model.addAttribute("businessLogList3",businessLogList);
        return "/product/product_list";
    }

    /**
     * 进入税点毛利设置页
     * @return
     */
    @RequiresPermissions(value = {"product:forPricing:setPoint,product:havePricing:setPoint"},logical = Logical.OR)
    @RequestMapping("/updatePoint")
    public String updatePoint(Model model,Long tid,@RequestParam(required = false,defaultValue = "0") String m){
        log.info("-------传入参数产品tid:"+tid+"-------------");
        //查询该商品的信息
        Product product = productSvr.getProjectByTid(tid);
        log.info("----------------查询出来产品信息product:"+product+"--------------------------");
        List<BusinessLog> businessLogList = businessLogService.findList(BusinessLog.BusinessTypeEnum.PRODUCT, tid);
        if(product!=null){

            if(product.getSeparateStatus()!=null&&product.getModalityStatus()!=null){
                model.addAttribute("m",1);
            }else{
                model.addAttribute("m",0);
            }
        }
        model.addAttribute("types",2);
        model.addAttribute("product1",product);
        model.addAttribute("businessLogList1",businessLogList);
        return "/product/product_list";
    }

    /**
     * 税点毛利设置
     * @param model
     * @param product 产品
     * @return
     */
    @RequestMapping(value = "/setPoint",method = RequestMethod.POST)
    public String setPoint(Model model,Product product,String m,String remark){
        log.info("----------------传入参数product:"+product+"--------------------------");
        try {
            productSvr.updateProduct(product,m,remark);
            businessLogService.save(BusinessLog.BusinessTypeEnum.PRODUCT,product.getTid(),BusinessLog.ContentEnum.SET_TAX_POINT,remark);
            auditTaskService.submit(WorkFlowEnum.CREATE_PRODUCT, FlowBusinessTypeEnum.PRODUCT,product.getTid(), FlowOperateTypeEnum.PASS);
        }catch (Exception e){
            e.printStackTrace();
        }

        return "redirect:/product/toList";
    }
    /**
     * 进入自留点位设置页
     * @param model
     * @return
     */
    @RequestMapping("/earingPoint")
    public String earingPoint(Model model,Long tid,@RequestParam(required = false,defaultValue = "0") String m){
        log.info("-------传入参数产品tid:"+tid+"-------------");
        //查询该商品的信息
        Product product = productSvr.getProductByTid(tid);
        List<BusinessLog> businessLogList = businessLogService.findList(BusinessLog.BusinessTypeEnum.PRODUCT, tid);
        log.info("----------------查询出来产品信息product:"+product+"--------------------------");
        if(product!=null){
            int count = 0;
            for (EaringPoint e: product.getEaringPointList()) {
                if(EaringPoint.TypeEnum.TYPE_STATUS_ALL.getValue().equals(e.getType())){
                    count ++;
                }
            }
            model.addAttribute("count",count);
            if(product.getEaringPointList().size()>0){
                model.addAttribute("m2",1);
            }else{
                model.addAttribute("m2",0);
            }
        }
        model.addAttribute("types",3);

        model.addAttribute("product2",product);
        model.addAttribute("businessLogList",businessLogList);
        return "/product/product_list";
    }

    /**
     * 设置自留点位
     * @param model
     * @param collectionForm
     * @param request
     * @return
     */
    @RequestMapping(value = "/setEarningPoint",method = RequestMethod.POST)
    public  String setEarningPoint(Model model, CollectionForm collectionForm, HttpServletRequest request,String m,String remark){
        log.info("-------传入参数collectionForm:"+collectionForm+"-------------");
        String earing = request.getParameter("earning");
        String earing1 = request.getParameter("earning1");
        String tid = request.getParameter("tid");
        try {
            productSvr.setEaringPoint(earing,earing1,tid,collectionForm.getCollectionForm(),m,remark);
            businessLogService.save(BusinessLog.BusinessTypeEnum.PRODUCT,Long.parseLong(tid),BusinessLog.ContentEnum.SET_EARNING_POINT,remark);
            auditTaskService.submit(WorkFlowEnum.CREATE_PRODUCT, FlowBusinessTypeEnum.PRODUCT,Long.parseLong(tid), FlowOperateTypeEnum.PASS);
        }catch (Exception e){
            e.printStackTrace();
        }
        return "redirect:/product/toList";
    }

    /**
     * 进入产品审核页
     * @param model
     * @return
     */
    @RequestMapping("/check")
    public String check(Model model,Long tid,String t){
        log.info("-------传入参数产品tid:"+tid+"t:"+t+"-------------");
        //查询该商品的信息
        Product product = productSvr.getProductByTid(tid);
        List<BusinessLog> businessLogList = businessLogService.findList(BusinessLog.BusinessTypeEnum.PRODUCT, tid);
        log.info("----------------查询出来产品信息product:"+product+"--------------------------");
        model.addAttribute("types",6);
        model.addAttribute("role",t);
        model.addAttribute("product3",product);
        model.addAttribute("businessLogList2",businessLogList);
        return "/product/product_list";
    }

    /**
     * 业务负责人审核
     * @param product
     * @return
     */
    @RequestMapping(value = "/checkProductByEmployee",method = RequestMethod.POST)
    @ResponseBody
    public Boolean checkProduct(Product product){
        log.info("----------------传入参数product:"+product+"--------------------------");
        Boolean flag = false;
        try {
            productSvr.updateProduct(product, null, null);
            businessLogService.save(BusinessLog.BusinessTypeEnum.PRODUCT,product.getTid(),BusinessLog.ContentEnum.PRODUCT_CHECK_PASS,product.getOpinion());
            auditTaskService.submit(WorkFlowEnum.CREATE_PRODUCT, FlowBusinessTypeEnum.PRODUCT,product.getTid(), FlowOperateTypeEnum.PASS);
            flag = true;
        }catch (Exception e){
            e.printStackTrace();
        }
        return flag;
    }

    /**
     * 财务经理审核
     * @param product
     * @return
     */
    @RequestMapping(value = "/checkProductByManager",method = RequestMethod.POST)
    @ResponseBody
    public Boolean checkProductByManager(Product product,Model model,RedirectAttributes redirectAttributes){
        log.info("----------------传入参数product:"+product+"--------------------------");
        Boolean flag = false;
        try {
            productSvr.updateProducts(product);
            businessLogService.save(BusinessLog.BusinessTypeEnum.PRODUCT,product.getTid(),BusinessLog.ContentEnum.PRODUCT_CHECK_PASS,product.getOpinion());
            auditTaskService.submit(WorkFlowEnum.CREATE_PRODUCT, FlowBusinessTypeEnum.PRODUCT,product.getTid(), FlowOperateTypeEnum.PASS);
            flag = true;
        }catch (Exception e){
            e.printStackTrace();
        }
        return flag;
    }

    /**
     * 改变产品状态
     * @param model
     * @param status
     * @param tid
     * @return
     */
    @RequestMapping("/useStatus")
    @ResponseBody
    public Boolean useStatus(Model model,Integer status,Long tid){
        log.info("-------------传入参数状态status："+status+"主键id："+tid+"-------------------------");
        Boolean flag = false;
        try {
            productSvr.updateProductStatus(status,tid);
            flag = true;
        }catch (Exception e){
            e.printStackTrace();
        }
        return flag;
    }

    /**
     * 检查该产品是否已被禁用
     * @param companyId
     * @return
     */
    /*@RequestMapping("/selectProductStatus")
    @ResponseBody
    public List<Product> selectProductStatus(Long companyId){
        List<Product> productList = productSvr.selectProductStatus(companyId);
        return productList;
    }*/

    /**
     * 驳回
     * @param product
     * @return
     */
    @RequestMapping("/reject")
    public String reject(Product product){
        log.info("----------------传入参数product:"+product+"--------------------------");
        try {
            productSvr.rejectProduct(product);
            businessLogService.save(BusinessLog.BusinessTypeEnum.PRODUCT,product.getTid(),BusinessLog.ContentEnum.PRODUCT_CHECK_REJECT,product.getOpinion());
            auditTaskService.submit(WorkFlowEnum.CREATE_PRODUCT, FlowBusinessTypeEnum.PRODUCT,product.getTid(), FlowOperateTypeEnum.REJECT, RejectNodeEnum.PRODUCT_OVER);
        }catch (Exception e){
            e.printStackTrace();
        }
        return "redirect:/product/toList";
    }

    /**
     * 查询所有有可用产品的保险公司
     * @return
     */
    @RequestMapping("/getCompany")
    @ResponseBody
    public List<Insurer> getCompany(){
        List<Insurer> insurerList = productSvr.getCompany();
        return insurerList;
    }

    /**
     * 删除
     * @param tid
     * @return
     */
    @RequestMapping("/deleteById")
    @ResponseBody
    public Boolean deleteById(Long tid){
        Boolean flag = false;
        try {
            productSvr.deleteById(tid);
            flag = true;
        }catch (Exception e){
            e.printStackTrace();
        }
        return flag;
    }

    /**
     * 校验产品唯一
     * @param companyId
     * @param type
     * @return
     */
    @RequestMapping("/checkProduct")
    @ResponseBody
    public Boolean checkProduct(Long companyId,Integer type){
        Boolean flag = true;
        Integer conut = productSvr.checkProduct(companyId,type);
        if (conut==0){
            flag = false;
        }
        return flag;
    }
    /**
     * 编辑提交时查询产品是否可用
     * @param productId
     * @return
     */
    @ResponseBody
    @RequestMapping("/checkedy")
    public OperateResult checkProduct(Long productId){
        OperateResult operateResult = productSvr.checkProductMessage(productId);
        return operateResult;
    }
}
